/*
 * @Author: your name
 * @Date: 2020-11-03 10:49:44
Vconsole
 * @LastEditTime: 2020-11-12 17:09:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /crowd-funding/src/utils/restApi.js
 */
import axios from 'axios'
import { serialize, isApp } from '@jmfe/jm-common'
import { UUID, WQ_BIZ } from './constants'
import { isProduction } from './utils'

// import CryptoJS from 'crypto-js'

// 线上域名
let HOST = '//api.m.jd.com'

// 预发域名
if (!isProduction()) {
	HOST = '//beta-api.m.jd.com'
}

export const def = {
	protocol: '',
	host: HOST,
	path: '/client.action',
}
// h5.m.jd.com/babelDiy/Zeus/P3Wx2QMBVrLFFTSfxS8pvYMoaE8/index.html?
const commonParams = {
	appid: 'wh5',
	client: 'wh5',
	clientVersion: '1.0.0',
	uuid: UUID,
}

const loginType =
	isApp('qq') || isApp('wx')
		? {
				loginType: 1,
				loginWQBiz: WQ_BIZ,
		  }
		: {}

const http = axios.create({
	baseURL: HOST,
	headers: {
		'Content-type': 'application/x-www-form-urlencoded',
	},
	withCredentials: true,
	timeout: 5000,
})

// 请求开始前 拦截器 处理通用参数
http.interceptors.request.use(
	(config) => {
		// const stringSign = Object.values(data).reduce((result, el, index) => {
		// 	if (index === 0) return el
		// 	return `${result}&${el}`
		// }, '')
		// const signValue = CryptoJS.HmacSHA256(stringSign, secretkey)

		if (config.method === 'get' || config.method === 'GET') {
			const { params } = config
			const serializeParams = {
				...loginType,
				...commonParams,
				...params,
				// signValue,
			}
			config.params = serializeParams
		} else {
			const { data } = config
			// post 请求序列化参数
			const serializeData = serialize({
				...loginType,
				...commonParams,
				...data,
				// signValue,
			})
			config.data = serializeData
		}
		return config
	},
	(err) => {
		return Promise.reject(err)
	}
)

export const restApi = ({ path = def.path, functionId, body = {}, method = 'POST' }) => {
	// path = '/betaApi'
	switch (method) {
		case 'POST': {
			return http({
				method: 'POST',
				url: path,
				data: {
					functionId,
					body: typeof body === 'object' ? JSON.stringify(body) : body,
				},
			}).then(({ data }) => data)
		}

		case 'GET': {
			return http({
				method: 'GET',
				url: path,
				params: {
					functionId,
					body: typeof body === 'object' ? JSON.stringify(body) : body,
				},
			}).then(({ data }) => data)
		}
		default:
			break
	}
}
